<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="售后类型" prop="afterSaleType">
        <el-select v-model="queryParams.afterSaleType" placeholder="请选择物料类型" clearable style="width: 200px">
          <el-option v-for="dict in afterSaleType_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="内部单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入内部单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="线上订单号" prop="orderLineNo">
        <el-input v-model="queryParams.orderLineNo" placeholder="请输入线上订单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="选择店铺" prop="shopsName">
        <el-input v-model="queryParams.shopsName" placeholder="请输入店铺" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="groupList">
      <el-table-column type="selection" width="55" />
      <el-table-column label="内部单号" prop="orderNo" width="200">
        <template #default="scope">
          <router-link :to="'/order/orderDetail?orderId=' + scope.row.id" class="link-type">
            <span>{{ scope.row.orderNo }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="售后类型" prop="afterSaleTypeName" width="120" />
      <el-table-column label="售后商品" prop="goodsImageUrl" :show-overflow-tooltip="true" width="120">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.detailsList.goodsImageUrl" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="售后件数" prop="goodsTotalNum" :show-overflow-tooltip="true" width="120">
        <template #default="scope">
          <div style="display: flex;align-items: center;">
            {{scope.row.goodsTotalNum}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="售后金额" prop="afterSaleAmount" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="售后时间" prop="afterSaleTime" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="售后说明" prop="afterSaleExplain" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="付款日期" prop="payTime" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="付款金额" prop="payAmount" :show-overflow-tooltip="true" width="100"></el-table-column>
      <el-table-column label="线上订单" align="center" width="200" prop="orderLineNo"></el-table-column>
      <el-table-column label="店铺名称" align="center" width="200" prop="shopsName"></el-table-column>
      <el-table-column label="生产状态" align="center" width="120" prop="orderProduceStatus"></el-table-column>
      <el-table-column label="退款原因" align="center" width="200" prop="refundReason"></el-table-column>
      <el-table-column label="原因图片" align="center" width="120" prop="refundReason">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.refundReasonImageUrl" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="责任人" align="center" width="200" prop="liableName"></el-table-column>
      <el-table-column label="罚款金额" align="center" width="200" prop="forfeitAmount"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">添加原因</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改物料配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="订单编号" prop="supplierId">
          <span>{{form.orderNo}}</span>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input v-model="form.refundReason" type="textarea" placeholder="请输入退款原因" />
        </el-form-item>
        <el-form-item label="责任人" prop="liableId">
          <span @click="selectKf">{{form.liableId?form.liableName:'请选择责任人'}}</span>
        </el-form-item>
        <el-form-item label="退款原因截图" prop="materialImageUrl">
          <el-upload ref="uploadRef" v-model:file-list="fileList" :headers="headers" class="upload-demo" :action="actionUrl"
            :data="{ type: 0, tenantGroupId: tenantGroupId }" name="file" accept=".jpeg,.png" :on-error="handleUploadSuccess" :on-success="handleUploadSuccess"
            :on-exceed="handleExceed">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="罚款金额" prop="forfeitAmount">
          <el-input-number v-model="form.forfeitAmount" type="textarea" placeholder="请输入罚款金额" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="备注说明" />
        </el-form-item>
      </el-form>
      <el-dialog title="选择用户" v-model="visible" width="900px" top="7vh">
        <el-form :model="UserqueryParams" ref="queryRef" :inline="true">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="UserqueryParams.userName" placeholder="请输入用户名称" clearable style="width: 200px" @keyup.enter="userhandleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="UserqueryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 200px" @keyup.enter="userhandleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="userhandleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="userresetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row>
          <el-table ref="refTable" :data="userList" @row-click="userhandleSelectionChange" height="260px">
            <el-table-column label="用户名称" prop="userName" :show-overflow-tooltip="true" />
            <el-table-column label="用户昵称" prop="nickName" :show-overflow-tooltip="true" />
            <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="usertotal > 0" :total="usertotal" v-model:page="UserqueryParams.pageNum" v-model:limit="UserqueryParams.pageSize"
            @pagination="usergetList" />
        </el-row>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSelectUser">确 定</el-button>
            <el-button @click="visible = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Aftersales">
  import {
    afterSalelist,
    afterSaleInfo,
    afterSaleEdit
  } from "@/api/order/order"
  import { listUser } from '@/api/system/user'
  import baseForm from "../hooks/useOrderBase";
  const { headers, actionUrl, fileList, fileList2, fileList3, tenantGroupId } = baseForm();
  const router = useRouter();
  const route = useRoute()
  const { proxy } = getCurrentInstance();
  const { afterSaleType_type } = proxy.useDict("afterSaleType_type");
  const groupList = ref([]);
  const open = ref(false);
  const appLicationList = ref([])
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const dateRange = ref([]);
  const menuOptions = ref([]);
  const menuExpand = ref(false);
  const menuNodeAll = ref(false);
  const deptExpand = ref(true);
  const deptNodeAll = ref(false);
  const deptOptions = ref([]);
  const openDataScope = ref(false);
  const menuRef = ref(null);
  const deptRef = ref(null);
  const userList = ref([])
  const usertotal = ref(null)
  const visible = ref(false)
  // 多选框选中数据
  function userhandleSelectionChange(row) {
    form.value.liableName = row.userName
    form.value.liableId = row.userId;
    form.value.deptId = row.deptId;
    form.value.deptName = row.dept ? row.dept.deptName : '';
    visible.value = false
  }

  function selectKf() {
    visible.value = true;
    usergetList()
  }
  /** 搜索按钮操作 */
  function userhandleQuery() {
    UserqueryParams.pageNum = 1
    usergetList()
  };
  // 查询表数据
  function usergetList() {
    listUser({ ...UserqueryParams.value }).then(res => {
      userList.value = res.rows
      usertotal.value = res.total
    })
  };
  /** 重置按钮操作 */
  function userresetQuery() {
    proxy.resetForm('queryRef')
    userhandleQuery()
  }
  const data = reactive({
    form: {},
    UserqueryParams: {
      pageNum: 1,
      pageSize: 10,
    },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      orderNo: '',
      orderLineNo: undefined,
      shopsName: undefined,
      afterSaleType: '',
    },
    rules: {

    },
  });
  const { queryParams, form, rules, UserqueryParams } = toRefs(data);

  /** 查询订单列表 */
  function getList() {
    loading.value = true;
    let formQueryParam = { ...queryParams.value };
    formQueryParam.expireTemp = formQueryParam.expireTemp == 0 ? '' : formQueryParam.expireTemp
    afterSalelist(proxy.addDateRange(formQueryParam, dateRange.value)).then(response => {
      groupList.value = response.rows
      total.value = response.total;
      loading.value = false;
    });
  }
  const uploadRef = ref();

  function handleExceed(files) {
    uploadRef.value.clearFiles();
    nextTick(() => {
      uploadRef.value.handleStart(files[0]);
      uploadRef.value.submit();
    });
  }
  // 上传成功回调
  function handleUploadSuccess(res, file) {
    // 如果上传成功
    if (res.code == 200) {
      fileList.value.push(res.data);
      fileList.value = fileList.value.filter((f) => f.url !== undefined);
      form.value.refundReasonImageUrl = fileList.value.map((label) => {
        return label.url
      }).join(',');
    } else {
      proxy.$modal.msgError("上传失败:" + res.msg);
    }
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      orderNo: '',
      orderLineNo: undefined,
      shopsId: undefined,
      orderProduceStatus: '',
    }
    handleQuery();
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const tenantGroupIds = row.tenantGroupId || ids.value;
    proxy.$modal.confirm('是否确认删除订单编号为"' + tenantGroupIds + '"的数据项?').then(function() {
      return delgroup(tenantGroupIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }


  /** 重置新增的表单以及其他数据  */
  function reset() {
    if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    deptExpand.value = true;
    deptNodeAll.value = false;
    form.value = {
      tenantGroupName: undefined,
      tenantGroupLinkName: undefined,
      tenantGroupLinkMobile: '',
      tenantGroupExpireStatus: 'F',
      tenantGroupAvl: 'Y',
      tenantCreateParams: []
    };
    proxy.resetForm("roleRef");
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
        if (form.value.id != undefined) {
          afterSaleEdit({ ...form.value }).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 修改订单 */
  function handleUpdate(row) {
    reset();
    form.value = { ...row };
    fileList.value = form.value.refundReasonImageUrl ? form.value.refundReasonImageUrl.split(',').map((res) => {
      return { name: res, url: res }
    }) : [];
    open.value = true;
    title.value = "添加原因";
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }

  getList();
</script>